import re
from rest_framework import serializers, exceptions
from django.db import transaction

from . import models
from framework.serializers import ModelSerializer


class CreateUserSerializer(ModelSerializer):
    password = serializers.CharField(write_only=True, required=False, label='密码')
    username = serializers.CharField(required=True, label='用户名')
    tel = serializers.CharField(required=True, label='手机号')

    class Meta:
        model = models.User
        fields = ('id', 'username', 'password', 'tel', 'name')

    @staticmethod
    def validate_tel(value):
        """验证手机格式"""
        pattern = r'^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$'
        if not re.search(re.compile(pattern), value):
            raise exceptions.ValidationError('手机号格式不正确')
        return value

    def create(self, validated_data):
        """创建用户设置密码"""
        queryset = models.User.objects.filter(username=validated_data['username'])
        if queryset.exists():
            raise exceptions.ValidationError('用户名已存在')
        password = validated_data.pop('password', None)
        with transaction.atomic():
            user = super().create(validated_data)
            if not password:
                password = validated_data['username']
            user.set_password(password)
            user.save()
            return user


class UserSerializer(ModelSerializer):
    datetime_fields = ('date_joined',)

    class Meta:
        model = models.User
        fields = ('id', 'username', 'name', 'created_at', 'updated_at', 'tel', 'date_joined')
